package org.homeworkadmin.admin.utils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * 文件上传工具类
 * @author ：shiqiaojie
 * 返回类型 String
 * 返回数据 图片路径
 */
public class FileUploadUtils {

    public static String saveFile(MultipartFile file, String uploadDir) throws IOException {
        File directory = new File(uploadDir);
        if (!directory.exists()) {
            directory.mkdirs();
        }

        File targetFile = new File(directory, file.getOriginalFilename());
        try (InputStream inputStream = file.getInputStream();
             FileOutputStream outputStream = new FileOutputStream(targetFile)) {
            byte[] buffer = new byte[1024];
            int length;
            while ((length = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, length);
            }
        }
        System.out.println("文件已成功保存到: " + targetFile.getAbsolutePath());
        return targetFile.getAbsolutePath();
    }
}
